﻿using System;
using BoatNGoat.Logic.Map;
using BoatNGoat.Server;
using SharpDX;

namespace BoatNGoat.Logic
{
    public class Goat : IUpdateable, IMobile
    {
        private readonly int _id;
        private readonly IMovementConstraint _moveChecker;
        private readonly IMobBehaviour _behaviour;

        public Goat(int id, IMovementConstraint moveChecker, IMobBehaviour behaviour)
        {
            _id = id;
            _moveChecker = moveChecker;
            _behaviour = behaviour;
        }

        private Vector2 _position;
        private Vector2 _velocity;  

        public void Update(ServerTime serverTime)
        {
            float time = (float)serverTime.ElapsedGameTime.TotalSeconds;
            _velocity = _behaviour.MakeDecision(serverTime, _position);

            Vector2 nextPosition = _position + _velocity*time;
            if (_moveChecker.CanMoveTo(CollisionBox(nextPosition)))
            {
                _position = nextPosition;
            }
            else
            {
                _velocity = Vector2.Zero;
            }
        }

        private MapBox2 CollisionBox(Vector2 position)
        {
            return new MapBox2
                {
                    Bottom = position.Y - Height/2.0,
                    Left = position.X - Width/2.0,
                    Right = position.X + Width/2.0,
                    Top = position.Y + Height/2.0
                };
        }

        public int EntityId
        {
            get { return _id; }
        }

        public int EntityType {
            get { return 1; }
        }
        public Vector2 Position { get { return _position; } set { _position = value; } }
        public Vector2 Velocity { get { return _velocity; } }


        public double Width
        {
            get { return 0.95; }
        }

        public double Height
        {
            get { return 0.95; }
        }
    }
}

